package com.fqcar.fqdf.service;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.fqcar.fqdf.core.http.UrlHelper;
import com.fqcar.fqdf.core.volley.OkHttpStack;

/**
 * @author 张枭
 * @version V1.0
 * @date 2017/3/21
 * @desc
 */
public class VolleySingleton {

    private static volatile VolleySingleton mInstance;
    private RequestQueue mRequestQueue;

    public VolleySingleton(Context context) {
        mRequestQueue = Volley.newRequestQueue(context.getApplicationContext(), OkHttpStack.getInstance());
        mRequestQueue.start();
    }

    /**
     * 先进行初始化才能正常使用
     *
     * @param context
     */
    public static void initInstance(Context context) {
        if (mInstance == null) {
            synchronized (UrlHelper.class) {
                if (mInstance == null) {
                    mInstance = new VolleySingleton(context);
                }
            }
        } else {
            throw new IllegalAccessError("initinstance only call one time");
        }
    }

    public static VolleySingleton getInstance() {
        if (mInstance == null) {
            throw new IllegalAccessError("initinstance first before call getinstance");
        }
        return mInstance;
    }


    public RequestQueue getRequestQueue() {
        return mRequestQueue;
    }

    public <T> void addToRequestQueue(Request<T> req) {
        mRequestQueue.add(req);
    }


    public <T> Request<T> addRequest(Request<T> request) {

        return mRequestQueue.add(request);
    }

    /**
     * 取消网络请求
     *
     * @param tag request的tag
     */
    public void cancel(String tag) {
        mRequestQueue.cancelAll(tag);
    }

    /**
     * 取消网络请求
     *
     * @param requestFilter request过滤器
     */
    public void cancel(RequestQueue.RequestFilter requestFilter) {
        mRequestQueue.cancelAll(requestFilter);
    }

    /**
     * 取消网络请求
     *
     * @param request request 请求
     */
    public void cancel(Request request) {
        mRequestQueue.cancelAll(request);
    }

    /**
     * 停止volley
     */
    public void stop() {
        if (mRequestQueue == null) {
            return;
        }
        mRequestQueue.stop();
    }
}
